<template>
<!-- 个人信息弹窗 -->
<div v-if="visible && !showResetPassword" class="dialog-overlay" @click="close">
  <div class="dialog" @click.stop>
    <div class="dialog__header">
      <h3 class="dialog__title">个人信息</h3>
      <button class="dialog__close" @click="close" aria-label="关闭">
        <svg viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
      </button>
    </div>
    
    <div class="dialog__content">
      <div class="profile-info" v-if="!editing">
        <div class="profile-avatar">
          <img :src="userAvatar" alt="avatar" />
        </div>
        
        <div class="info-list">
          <div class="info-item">
            <span class="info-label">账号</span>
            <span class="info-value">{{ userAccount || '—' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">昵称</span>
            <span class="info-value">{{ userName || '—' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">角色</span>
            <span class="info-value">{{ userRole || 'user' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">注册时间</span>
            <span class="info-value">{{ formatDate(createTime) }}</span>
          </div>
        </div>

        <div class="profile-actions">
          <button class="btn" @click="editing = true">编辑资料</button>
          <button class="btn btn--primary" @click="showResetPassword = true;">重置密码</button>
        </div>
      </div>

      <div v-else class="edit-form">
        <div class="form-group">
          <label class="form-label">用户昵称</label>
          <input v-model="editForm.userName" class="form-input" placeholder="请输入昵称" />
        </div>
        <div class="form-group">
          <label class="form-label">头像URL</label>
          <input v-model="editForm.userAvatar" class="form-input" placeholder="请输入头像URL(可选)" />
          <div class="avatar-preview" v-if="editForm.userAvatar">
            <img :src="editForm.userAvatar" alt="预览" />
          </div>
        </div>
      </div>
    </div>
    
    <div class="dialog__footer" v-if="!editing">
      <button class="btn btn--ghost" @click="close">关闭</button>
    </div>
    <div class="dialog__footer" v-else>
      <button class="btn btn--ghost" @click="cancelEdit">取消</button>
      <button class="btn btn--primary" :disabled="saving || !canSave" @click="saveEdit">
        <span v-if="saving">保存中...</span>
        <span v-else>保存</span>
      </button>
    </div>
  </div>
</div>

<!-- 重置密码弹窗 - 独立渲染，避免层级冲突 -->
<ResetPasswordDialog 
  v-if="showResetPassword"
  :visible="showResetPassword" 
  @close="showResetPassword = false"
  @success="onResetSuccess"
/>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { useUserStore } from '../stores/user';
import ResetPasswordDialog from './ResetPasswordDialog.vue';

const props = defineProps({
  visible: { type: Boolean, default: false },
  user: { type: Object, default: () => ({}) }
});
const emit = defineEmits(['close']);

const userStore = useUserStore();

const showResetPassword = ref(false);
const editing = ref(false);
const saving = ref(false);
const editForm = ref({ id: undefined, userName: '', userAvatar: '' });

const userAvatar = computed(() => props.user?.userAvatar || '/user-avatar.svg');
const userAccount = computed(() => props.user?.userAccount);
const userName = computed(() => props.user?.userName || props.user?.userAccount);
const userRole = computed(() => props.user?.userRole || 'user');
const createTime = computed(() => props.user?.createTime);

watch(() => props.visible, (v) => {
  if (v) {
    // 初始化编辑表单
    editForm.value = {
      id: props.user?.id,
      userName: props.user?.userName || '',
      userAvatar: props.user?.userAvatar || ''
    };
    editing.value = false;
  }
});

const canSave = computed(() => {
  return !!editForm.value.id && (editForm.value.userName?.trim()?.length > 0);
});

function close() {
  emit('close');
}

function cancelEdit() {
  editing.value = false;
}

function formatDate(date) {
  if (!date) return '—';
  try { return new Date(date).toLocaleDateString('zh-CN'); } catch { return '—'; }
}

async function saveEdit() {
  if (!canSave.value || saving.value) return;
  saving.value = true;
  try {
    const payload = {
      id: editForm.value.id,
      userName: editForm.value.userName?.trim(),
      userAvatar: editForm.value.userAvatar?.trim() || undefined
    };
    await userStore.updateUser(payload);
    editing.value = false;
    alert('保存成功');
  } catch (e) {
    alert(e.message || '保存失败');
  } finally {
    saving.value = false;
  }
}

function onResetSuccess() {
  showResetPassword.value = false;
  alert('密码重置成功');
}
</script>

<style scoped>
.dialog-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.5); display: grid; place-items: center; z-index: 1000; }
.dialog { background: #fff; border-radius: 12px; box-shadow: 0 20px 60px rgba(0,0,0,.2); width: 90%; max-width: 520px; max-height: 90vh; overflow: hidden; }
.dialog__header { display: flex; align-items: center; justify-content: space-between; padding: 20px 24px; border-bottom: 1px solid var(--border-color); }
.dialog__title { font-size: 18px; font-weight: 600; margin: 0; }
.dialog__close { width: 32px; height: 32px; border-radius: 50%; border: none; background: transparent; display: grid; place-items: center; cursor: pointer; }
.dialog__close:hover { background: #f5f6f7; }
.dialog__content { padding: 24px; }
.profile-info { text-align: center; }
.profile-avatar { margin-bottom: 20px; }
.profile-avatar img { width: 80px; height: 80px; border-radius: 50%; border: 2px solid var(--border-color); }
.info-list { display: grid; gap: 12px; margin-bottom: 24px; }
.info-item { display: grid; grid-template-columns: 80px 1fr; align-items: center; padding: 12px 0; border-bottom: 1px solid #f0f0f0; }
.info-label { color: var(--text-secondary); font-size: 14px; }
.info-value { font-weight: 600; color: var(--text-primary); }
.profile-actions { display: flex; justify-content: center; gap: 12px; }
.dialog__footer { padding: 16px 24px; border-top: 1px solid var(--border-color); display: flex; justify-content: flex-end; gap: 12px; }
.btn { padding: 8px 16px; border-radius: 8px; border: 1px solid var(--border-color); background: #fff; cursor: pointer; }
.btn--ghost { color: var(--text-primary); }
.btn--primary { background: #3b82f6; color: #fff; border-color: #3b82f6; }
.btn:hover { background: #f5f6f7; }
.btn--primary:hover { background: #2563eb; }

.edit-form { display: grid; gap: 16px; }
.form-group { display: grid; gap: 8px; }
.form-label { font-size: 14px; font-weight: 600; color: #374151; }
.form-input { padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px; transition: border-color 0.2s; }
.form-input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 2px rgba(59,130,246,.1); }
.avatar-preview img { width: 56px; height: 56px; border-radius: 50%; border: 1px solid var(--border-color); margin-top: 8px; }
</style>
